package io.summer.basis.config;

import io.summer.basis.core.http.CustomSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Spring Boot >= 1.4 Spring Boot不再自动定义一个RestTemplate
 * 这里使用okhttp
 *
 * @author Moonlight
 */
@Configuration
@Slf4j
public class OkHttpConfig {
  private final static int MAX_IDLE_CONNECTIONS = 5;
  /**
   * 连接保活时间(秒)
   */
  private final static long KEEP_ALIVE_SECOND = 300L;

  @Bean
  public OkHttpClient okHttpClient() {
    return new OkHttpClient.Builder()
      .sslSocketFactory(Objects.requireNonNull(CustomSSLSocketFactory.socketFactory()),
        CustomSSLSocketFactory.x509TrustManager())
      .retryOnConnectionFailure(true)
      .connectionPool(pool())
      .connectTimeout(Duration.ofMillis(1000))
      .readTimeout(Duration.ofMillis(2000))
      .writeTimeout(Duration.ofMillis(2000))
      .build();
  }

  private ConnectionPool pool() {
    return new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_SECOND, TimeUnit.SECONDS);
  }
}
